<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<script src="../../resources/js-test.js"></script>
</head>
<body>
<script>
description("Tests RTCDataChannel.");

var pc = null;
var pc2 = null;
var dc = null;

function dc_onopen() {
    // We are not allowed to send shared array buffers
    // See https://github.com/whatwg/html/issues/5380 for why not `new SharedArrayBuffer()`
    shouldThrow("dc.send(new Uint8Array(new (new WebAssembly.Memory(" +
                   "{ shared:true, initial:0, maximum:0 }).buffer.constructor)()));");

    // Try to fill the data channel send queue, it should throw an exception.
    // This is inherently racy, but the JS speeds are currently orders of magnitude
    // faster than the underlying networking code and should pass quickly.
    // See https://w3c.github.io/webrtc-pc/#datachannel-send

    dc.onerror = () => {
        testFailed("Data Channel onerror should not be called on a full send queue");
    }

    var s = "0".repeat(256 * 1024); // 256KiB
    try {
        for(let i = 0; i < 1000; ++i) {
            dc.send(s);
        }
    } catch (e) {
	testPassed("When the data channel send queue is full, send() throws an exception");
    }

    setTimeout(() => {
        // After send() previously failed, we should still have an open data channel.
        shouldBeEqualToString('dc.readyState', 'open');
        dc.close();
        finishJSTest();
    });
}

async function connect_pcs(pc_a, pc_b) {
  pc_a.onicecandiate = function(event) {
    if (event.candidate) {
      pc_b.addIceCandidate(event.candidate);
    }
  }
  pc_b.onicecandidate = function(event) {
    if (event.candidate) {
      pc_a.addIceCandidate(event.candidate);
    }
  }
  await pc_a.setLocalDescription();
  await pc_b.setRemoteDescription(pc_a.localDescription);
  await pc_b.setLocalDescription();
  await pc_a.setRemoteDescription(pc_b.localDescription);
}

pc = new RTCPeerConnection();
pc2 = new RTCPeerConnection();

dc = pc.createDataChannel("label");
dc.onopen = dc_onopen;

connect_pcs(pc, pc2);

window.jsTestIsAsync = true;
window.successfullyParsed = true;
</script>
</body>
</html>
